import { Decorator } from "../core/Decorator";
import { Tick } from "../core/Tick";
import { ActionStatus } from "../core/BaseNode";

export class Limiter extends Decorator {

    maxLoop: number = 1;

    constructor(params?: any) {
        super(params);
        params = params || {maxLoop: 1};
        this.name = 'Limiter';
        this.title = 'Limit <maxLoop> Activations';
        this.properties = params
        this.maxLoop = params.maxLoop || 1;
    }

    open(tick: Tick) {
        let i = tick.blackboard.get('i', tick.tree.id, this.id);
        if (!i) {
            i = 0;
        }
        tick.blackboard.set('i', i, tick.tree.id, this.id);
    
    }

    tick(tick: Tick) : ActionStatus {
        if (!this.child) {
            return ActionStatus.ERROR;
        }
        let i = tick.blackboard.get('i', tick.tree.id, this.id);
        if (i < this.maxLoop) {
            let status = this.child._execute(tick);
            if (status === ActionStatus.SUCCESS || status === ActionStatus.FAILURE) {
                tick.blackboard.set('i', i + 1, tick.tree.id, this.id);
            }
            return status;
        }
        return ActionStatus.FAILURE;
    }
}